<template>
  <div class="registerElement">
    <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-width="100px">
      <el-form-item label="邮箱：" prop="username">
        <el-input v-model="ruleForm.username" @keydown.enter="register" />
      </el-form-item>
      <el-form-item label="密码：" prop="password">
        <el-input type="password" v-model="ruleForm.password" @keydown.enter="register" />
      </el-form-item>
      <el-form-item label="验证码：" prop="code">
        <div style="display: flex">
          <el-input v-model="ruleForm.code" @keydown.enter="register" />
          <div class="login-code">
            <el-button @click="getCode" :disabled="getBtn !== '获取'">{{ getBtn }}</el-button>
          </div>
        </div>
      </el-form-item>
    </el-form>

    <div style="width: 100%; text-align: center">
      <el-button type="primary" id="btn" @click="register">注册</el-button>
    </div>
  </div>
</template>

<script setup>
const httpService = inject('httpService')
const util = inject('util')

// 表单数据
const ruleForm = reactive({
  username: '',
  password: '',
  code: '',
})

// 表单校验规则
const rules = {
  username: [{ required: true, message: '请输入帐号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
}

// 表单 ref 引用
const ruleFormRef = ref()

// 获取按钮倒计时状态
const getBtn = ref('获取')

// 注册方法
const register = () => {
  ElMessageBox.confirm('是否确认注册？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    ruleFormRef.value.validate(valid => {
      if (valid) {
        httpService.post('/sys-login/register', ruleForm).then(() => {
          ruleForm.username = ''
          ruleForm.password = ''
          ruleForm.code = ''
          ElMessage.success('注册成功！')
        })
      }
    })
  })
}

// 获取验证码
const getCode = () => {
  if (!ruleForm.username) {
    ElMessage.error('请输入邮箱地址！')
    return
  }

  httpService.get(`/sys-login/getEmailCode/${ruleForm.username}`, {}).then(() => {
    ElMessage.success('获取成功，请通过邮箱查看验证码！')
    let countdown = 60
    getBtn.value = countdown

    const timer = setInterval(() => {
      countdown--
      if (countdown <= 0) {
        getBtn.value = '获取'
        clearInterval(timer)
      } else {
        getBtn.value = countdown
      }
    }, 1000)
  })
}
</script>

<style scoped>
.login-code {
  margin-left: 10px;
}
</style>
